package tomsung.cloud.agdc.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import tomsung.cloud.agdc.bean.City;
import tomsung.cloud.agdc.bean.District;
import tomsung.cloud.agdc.bean.Province;
import tomsung.cloud.agdc.model.JsonObject;
import tomsung.cloud.agdc.model.JsonRequest;
import tomsung.cloud.agdc.model.JsonResponse;
import tomsung.cloud.agdc.service.CityService;
import tomsung.cloud.agdc.service.DistrictService;
import tomsung.cloud.agdc.service.ProvinceService;

@Controller
public class AddressController extends CommonController{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private ProvinceService provinceService;
	
	@Autowired
	private CityService cityService;
	
	@Autowired
	private DistrictService districtService;
	
	@ResponseBody
	@RequestMapping(value = "/address", method = RequestMethod.POST)
	protected JsonObject transer(final HttpServletRequest request, @RequestBody JsonRequest req) {
		return super.transer(request, req);
	}
	/**
	 * 获取全国省市县
	 * @return
	 */
	public JsonResponse GET_ALL_ADDRESS(JsonRequest req) {
		JsonResponse res = req.getRep();
		try
		{	
			List<Province> pros = provinceService.getAllProvinces();
			res.V.put("ADDRESS", pros);
			List<City> citys = cityService.getAllCitys();
			for (Province pro : pros)
			{
				List<City> c = new ArrayList<City>();
				for (City city : citys)
				{
					if (pro.getProvinceid() == city.getProvinceid())
					{
						c.add(city);
					}
				}
				pro.setCitys(c);
			}
		}
		catch(Exception e)
		{
			res.R = false;
			res.setErrorMsg("获取全国省市失败。");
			logger.error(e.getMessage(), e);
		}
		return res;
	}

	public JsonResponse GET_ADDRESS_IDS(JsonRequest req) {
		JsonResponse res = req.getRep();
		try
		{	
			int provinceId = (Integer)req.V.get("PROVINCEID");
			int cityId = (Integer)req.V.get("CITYID");
			int districtId = (Integer)req.V.get("DISTRICTID");
			
			Province province = provinceService.selectProvince(provinceId);
			City city = cityService.selectCity(cityId, provinceId);
			District district = districtService.selectDistrict(districtId, cityId);
			
			res.V.put("PROVICENAME", province.getProvincename());
			res.V.put("CITYNAME", city.getCityname());
			res.V.put("DISTRICTNAME", district.getDistrictname());
			
		}
		catch(Exception e)
		{
			res.R = false;
			res.setErrorMsg("获取全国省市失败。");
			logger.error(e.getMessage(), e);
		}
		return res;
	}
	
}
